package com.imooc.sell.controller;

import com.imooc.sell.VO.ProductInfoVo;
import com.imooc.sell.VO.ProductVo;
import com.imooc.sell.VO.ResultVo;
import com.imooc.sell.dataobject.ProductCategory;
import com.imooc.sell.dataobject.ProductInfo;
import com.imooc.sell.service.CategoryService;
import com.imooc.sell.service.ProductInfoService;
import com.imooc.sell.utils.ResultVoUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/buyer/product")
public class BuyerProductController {

  @Autowired
  private ProductInfoService productInfoService;

  @Autowired
  private CategoryService categoryService;

  //获取商品分类以及子级
  @GetMapping("/list")
  public ResultVo list() {
    //1. 查询所有上架的商品
    List<ProductInfo> productInfoList = productInfoService.findUpAll();

    // 第二步的前提 先得到所有上架商品的id
    List<Integer> productIds = new ArrayList<Integer>();
    for (ProductInfo productInfo : productInfoList) {
      productIds.add(productInfo.getCategoryType());
    }
    //2. 从所有商品里面查询类目
    List<ProductCategory> productCategoryList = categoryService.findByCategoryTypeIn(productIds);


    //3. 数据拼装,外层是商品类型，商品类型内层是商品详情
    List<ProductVo> productResult = new ArrayList<ProductVo>();

    for (ProductCategory productCategory : productCategoryList) {
      ProductVo productVo = new ProductVo();
      productVo.setProductType(productCategory.getCategoryType());
      productVo.setProductName(productCategory.getCategoryName());

      List<ProductInfoVo> productInfoVoList = new ArrayList<ProductInfoVo>();
      for (ProductInfo productInfo : productInfoList) {
        //如果商品的类目与外层的类目相同
        if (productInfo.getCategoryType().equals(productCategory.getCategoryType())) {
          ProductInfoVo productInfoVo = new ProductInfoVo();
          //拷贝一份对象
          BeanUtils.copyProperties(productInfo, productInfoVo);
          productInfoVoList.add(productInfoVo);
        }
      }
      productVo.setFoods(productInfoVoList);
      productResult.add(productVo);
    }
    return ResultVoUtil.success(productResult);
  }
}
